package sv.net;

import java.net.*;
import java.io.*;


public class NetworkIOClient extends Thread {

	private NetworkIO connection;
	private Socket server;
	private InputStream input;
	private OutputStream output;
	private boolean running = true;

	
	NetworkIOClient(NetworkIO pConnection) {
		this.connection = pConnection;
		this.running = true;
	}
	
	
	int connect(String host) {
		try {
			this.server = new Socket(host, NetworkIO.port);
			this.input = this.server.getInputStream();
			this.output = this.server.getOutputStream();
			//this.start();
			return 0;
		} catch (UnknownHostException e) {
			return -1;
		} catch (IOException e) {
			return -2;
		}
	}
	
	
	synchronized int send(int command, int field) {
		try {
			output.write(command);
			output.write(field);
			output.flush();
			return input.read();
		} catch (IOException e) {
			return -2;
		}
	}
	
	int disconnect() {
		try {
			server.close();
			input.close();
			output.close();
			this.running = false;
			return 0;
		} catch (IOException e) {
			return -2;
		}
	}
	
	
	public void run() {
		int i = -1;
		try {
			this.input = this.server.getInputStream();
			this.output = this.server.getOutputStream();
		} catch (IOException e) {}
		while (running) {
			try {
				i = input.read();
				while (i < 0) i = input.read();
				int command = i;
				int field = input.read();
				output.write(NetworkIO.MSG_RECEIVED);
				output.flush();
				connection.message(command,field);
			} catch (IOException e) {}
		}
		try {
			input.close();
			output.close();
		} catch (IOException e) {}
	}
	
	
}